#!/usr/bin/env python
# -*- coding: utf-8 -*-

from threading import Timer

import datetime
import MysqlUtils
import YunPian
import Config

import sys
reload(sys)
sys.setdefaultencoding('utf-8')


def monitor():
    """
    监控函数
    :return:
    """
    print "监控执行 -- %s" % datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    # 当前检查执行时间
    now = datetime.datetime.now()
    db = MysqlUtils.MysqlHelper()
    # 凌晨12点的时候，删除一天前的提醒记录
    if now.hour == 0 and now.minute == 3:
        db.dml("DELETE FROM natgas_messagerecord WHERE add_time < curdate()")
    # 读取满足提醒条件的异常数据（10分钟内）
    abnormal_data = db.query("SELECT f.id, f.flowmeter_name, s.name as sname, c.name as cname, m.message_switch, "
                             "m.notify_condition, m.alert_freq,count(*) as data_count FROM natgas_abnormaldata d, "
                             "natgas_flowmeterreg f, natgas_concentratorreg c, natgas_site s, "
                             "natgas_messagesettings m WHERE d.flowmeter_id=f.id AND f.cno_id=c.id AND "
                             "c.site_id=s.id AND s.company_id=m.company_id AND "
                             "d.add_time >= DATE_SUB(NOW(),INTERVAL 10 MINUTE)  "
                             "GROUP BY f.flowmeter_name HAVING data_count>m.notify_condition")
    # 遍历提醒
    for data in abnormal_data:
        # 是否需要发送短信，默认需要发送
        is_send = True
        # 检查上一次提醒的时间
        add_time = db.query(
            "SELECT add_time FROM natgas_messagerecord WHERE flowmeter_id=%s ORDER BY id desc" % data['id']
        )
        if len(add_time) > 0:
            if not data['message_switch']:
                continue
            # 计算当前时间距离上一次提醒时间是否小于等于间隔时间（不满足间隔频率不发送短信）
            if (int((now-add_time[0]['add_time']).seconds/60)) <= int(data['alert_freq']):
                # 不需发送短信
                is_send = False
        if is_send:
            # 发送短信
            msg_content = '【苍南仪表】远程监控中心提醒：%s-%s-%s的流量计一分钟内出现了%s条异常数据，请及时检查（%s）' \
                          % \
                          (data['sname'], data['cname'], data['flowmeter_name'], data['data_count'], now.strftime("%Y-%m-%d %H:%M:%S"))
            print msg_content
            # 查询流量计绑定用户的电话号码
            user_list = db.query(
                "SELECT u.id, u.phone FROM natgas_flowmeterreg_user f, natgas_user u WHERE f.user_id=u.id "
                "AND f.flowmeterreg_id='%s'" % data['id']
            )
            send_time = now.strftime("%Y-%m-%d %H:%M:%S")
            for user in user_list:
                print '给%s发短信，短信内容：%s' % (user['phone'], msg_content)
                YunPian.send_sms(msg_content, user['phone'])
                # 写入短信发送记录
                db.dml(
                    "INSERT INTO natgas_messagerecord(flowmeter_id, user_id, content, add_time) "
                    "VALUES('%s','%s','%s','%s')"
                    %
                    (data['id'], user['id'], msg_content, send_time)
                )
    # 每日八点二十到八点三十检查日用气量是否超出设定，超出设定范围则发送短信通知
    if now.hour == 8 and 20 <= now.minute <= 30:
        # 昨天的日期
        yesterday = (now - datetime.timedelta(days=1)).strftime("%Y-%m-%d")
        # 查询超出范围且满足短信发送条件的数据
        sql="""
        select nfdt.id, nfr.id flowmeter_id, nu.id user_id,nfdt.flowmeter_b, nfr.flowmeter_name,nu.phone,ns.`name` sname,
        ncr.`name` cname,DATE_FORMAT(nfdt.add_time, '%%Y-%%m-%%d') add_time from natgas_flowmeterdatadaytotal nfdt,
        natgas_flowmeterreg nfr, natgas_user nu, natgas_flowmeterreg_user nfu, natgas_messagesettings nms,
        natgas_site ns, natgas_concentratorreg ncr where nfu.user_id=nu.id and nfu.flowmeterreg_id=nfr.id
        and nfdt.flowmeter_id=nfr.id and nu.company_id=nms.company_id and nfr.cno_id=ncr.id and ncr.site_id=ns.id
        and DATE_FORMAT(nfdt.add_time,'%%Y-%%m-%%d')='%s' and nfdt.is_notice=false
        and (nfdt.flowmeter_b>nfr.ryq_b_max or nfdt.flowmeter_b<nfr.ryq_b_min) and nms.message_switch=true
        """ % yesterday
        send_list = db.query(sql)
        send_time = now.strftime("%Y-%m-%d %H:%M:%S")
        for send in send_list:
            msg_content = '【苍南仪表】远程监控中心提醒：%s-%s-%s的流量计%s的日用气量为%s，超出限定范围，请及时检查（%s）'\
                          % (send['sname'], send['cname'], send['flowmeter_name'], send['add_time'], send['flowmeter_b'], now.strftime("%Y-%m-%d %H:%M:%S"))
            print '给%s发短信，短信内容：%s' % (send['phone'], msg_content)
            # 发送短信
            YunPian.send_sms(msg_content, send['phone'])
            # 修改该条数据的发送状态
            db.dml(
                "update natgas_flowmeterdatadaytotal set is_notice=true where id=%s "% send["id"]
            )
            # 写入短信发送记录
            db.dml(
                "INSERT INTO natgas_messagerecord(flowmeter_id, user_id, content, add_time) "
                "VALUES('%s','%s','%s','%s')"
                %
                (send['flowmeter_id'], send['user_id'], msg_content, send_time)
            )

    # 关闭数据库连接
    db.close()
    # 定时执行
    Timer(Config.TIMER_INTERVAL, monitor).start()

if __name__ == '__main__':
    monitor()

